import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import axios from "axios";
import { Skeleton, ActionBar } from "react-vant";
import { ListItemType } from "../home";
import { CartO, ChatO, ShopO } from "@react-vant/icons";
import { useDispatch } from "react-redux";
import { addCarItemActionCreator } from "../../store/car/carActions";
import { useCar } from "../../hooks";
import { addUserBrowHistoryActionCreator } from "../../store/user/userReducer";
import { useAppSelector } from "../../store";
const Index: React.FC = () => {
  const params = useParams();
  const dispatch = useDispatch();
  const navigate = useNavigate()
  const [item, setItem] = useState<ListItemType | null>(null);
  // 骨架屏状态
  const [loading, setLoading] = useState(true);
  const { count } = useCar()
  const token = useAppSelector(state => state.user.token)
  const handleAdd = () => {
    // 验证是否登录
    if(!token) { navigate('/login'); return  };
    // 加入购物车
    if (item) dispatch(addCarItemActionCreator(item));
  };

  useEffect(() => {
    // 根据id 请求详情数据
    axios.get("/api/detail/" + params.id).then((resp) => {
      setItem(resp.data.data);
      // 关闭骨架屏
      setLoading(false);
    });
    // 记录用户浏览
    dispatch(addUserBrowHistoryActionCreator(params.id as string))
  }, []);
  return (
    <div>
      {/* 默认展示：骨架屏 */}
      <Skeleton
        loading={loading}
        row={0}
        avatar
        avatarShape="square"
        avatarSize="350px"
      >
        <img src={item?.url} alt="" width="100%" />
      </Skeleton>
      <Skeleton loading={loading} title style={{ marginTop: 10 }}>
        <h3>{item?.title}</h3>
        <p>{item?.desc}</p>
      </Skeleton>

      <ActionBar>
        <ActionBar.Icon
          icon={<ChatO />}
          text="客服"
          onClick={() => console.log("chat click")}
        />
        <ActionBar.Icon
          icon={<CartO />}
          text="购物车"
          badge={{ content: count }}
          onClick={() => navigate('/car')}
        />
        <ActionBar.Icon
          icon={<ShopO />}
          text="店铺"
          onClick={() => console.log("shop click")}
        />
        <ActionBar.Button
          type="danger"
          text="立即购买"
          onClick={() => handleAdd()}
        />
      </ActionBar>
    </div>
  );
};

export default Index;
